package com.item.yxlottery.yxlottery.activity;

/*
 *------------------------------
 * @创建者      Administrator
 * @创建时间    2017/1/16 14:17
 * @文件描述    注册界面
 *------------------------------
 */

import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.utils.RegexUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.item.yxlottery.yxlottery.R;
import com.item.yxlottery.yxlottery.base.BaseActivity;
import com.item.yxlottery.yxlottery.callback.MyStringCallBack;
import com.item.yxlottery.yxlottery.common.Constant;
import com.item.yxlottery.yxlottery.utils.UrlUtil;
import com.item.yxlottery.yxlottery.views.ClearEditText;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

public class RegistActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.cet_regist_phone)
    ClearEditText mCetPhone;

    @Bind(R.id.cet_regist_authcode)
    ClearEditText mCetAuthcode;

    @Bind(R.id.bt_regist_getauthcode)
    Button mBtGetAuthcode;

    @Bind(R.id.all_regist_autocode)
    LinearLayout mAllAutoCode;

    @Bind(R.id.cet_regist_fristpassword)
    ClearEditText mCetFristPassword;

    @Bind(R.id.cet_regist_secondpassword)
    ClearEditText mCetSecondPassword;

    @Bind(R.id.all_regist_password)
    LinearLayout mAllPassword;

    @Bind(R.id.bt_regist_next)
    Button mBtNext;

    @Bind(R.id.tv_regist_login)
    TextView mTvLogin;

    @Bind(R.id.all_regist_wraning)
    LinearLayout mAllWraning;

    private TextView mTvActionBarTitle;
    private boolean mNextClick = false;
    private String mPhoneNumber = "";
    private String mAuthCode = "";

    @Override
    protected void setCustomActionBar(ImageButton ibActionbarLeft, TextView tvActionBarTitle, ImageButton ibActionbarRight, AutoRelativeLayout layoutActionbar) {
        ibActionbarLeft.setImageResource(R.drawable.leftarrow);
        ibActionbarLeft.setOnClickListener(this);
        ibActionbarRight.setVisibility(View.GONE);
        mTvActionBarTitle = tvActionBarTitle;
        mTvActionBarTitle.setText("手机验证");
    }

    @Override
    protected View initView() {
        View view = View.inflate(this, R.layout.activity_regist, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        mBtGetAuthcode.setSelected(false);
        String number = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
        if (number != null) {
            mCetPhone.setText(number);
            mCetPhone.setSelection(number.length());
        }
    }

    @Override
    protected void initEvent() {
        mBtGetAuthcode.setOnClickListener(this);
        mBtNext.setOnClickListener(this);
        mTvLogin.setOnClickListener(this);
        mCetPhone.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (RegexUtils.isMobileExact(charSequence)) {
                    mCetPhone.setTextColor(Color.BLACK);
                } else {
                    mCetPhone.setTextColor(Color.RED);
                }
                mCetPhone.setSelection(charSequence.length());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mCetFristPassword.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() < 6) {
                    mCetFristPassword.setTextColor(Color.RED);
                } else {
                    mCetFristPassword.setTextColor(Color.BLACK);
                }
                mCetFristPassword.setSelection(charSequence.length());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mCetSecondPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() < 6) {
                    mCetSecondPassword.setTextColor(Color.RED);
                } else {
                    mCetSecondPassword.setTextColor(Color.BLACK);
                }
                mCetSecondPassword.setSelection(charSequence.length());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_actionbar_left:
            case R.id.tv_regist_login:
                finish();
                break;
            case R.id.bt_regist_getauthcode://获取验证码
                String phone = mCetPhone.getText().toString();
                if (phone.isEmpty()) {
                    ToastUtils.showShortToastSafe(this, "手机号码不能为空");
                    return;
                }
                if (mCetPhone.getCurrentTextColor() == Color.RED) {
                    ToastUtils.showShortToastSafe(this, "手机号码格式不正确");
                    return;
                }
                MyCounttDownTimer counttDownTimer = new MyCounttDownTimer(61000, 1000);
                counttDownTimer.start();
                mBtGetAuthcode.setClickable(false);
                mBtGetAuthcode.setSelected(true);
                OkHttpUtils.post().url(UrlUtil.getValidUrl()).addParams("mobile", phone).build().execute(new MyStringCallBack(this, false) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject parse = (JSONObject) JSON.parse(response);
                        if (parse.getString("error_code").equals(Constant.SUCCESS)) {

                        }
                    }
                });
                break;
            case R.id.bt_regist_next://下一步/注册
                if (mNextClick == false) {
                    mPhoneNumber = mCetPhone.getText().toString();
                    mAuthCode = mCetAuthcode.getText().toString();
                    if (mPhoneNumber.isEmpty()) {
                        ToastUtils.showShortToastSafe(this, "手机号码不能为空");
                        return;
                    }
                    if (mCetPhone.getCurrentTextColor() == Color.RED) {
                        ToastUtils.showShortToastSafe(this, "手机号码格式不正确");
                        return;
                    }
                    if (mAuthCode.isEmpty()) {
                        ToastUtils.showShortToastSafe(this, "验证码不能为空");
                        return;
                    }
                    mNextClick = true;
                    mTvActionBarTitle.setText("设置密码");
                    mBtNext.setText("注册");
                    mAllAutoCode.setVisibility(View.GONE);
                    mAllPassword.setVisibility(View.VISIBLE);
                    mTvLogin.setVisibility(View.GONE);
                    mAllWraning.setVisibility(View.VISIBLE);
                } else {
                    String fristPassWord = mCetFristPassword.getText().toString();
                    String secondPassWord = mCetSecondPassword.getText().toString();
                    if (fristPassWord.isEmpty()) {
                        ToastUtils.showShortToastSafe(this, "登录密码不能为空");
                        return;
                    }
                    if (mCetFristPassword.getCurrentTextColor() == Color.RED) {
                        ToastUtils.showShortToastSafe(this, "登录密码格式不正确");
                        return;
                    }
                    if (secondPassWord.isEmpty()) {
                        ToastUtils.showShortToastSafe(this, "确认密码不能为空");
                        return;
                    }
                    if (mCetSecondPassword.getCurrentTextColor() == Color.RED) {
                        ToastUtils.showShortToastSafe(this, "确认密码格式不正确");
                        return;
                    }
                    if (!secondPassWord.equals(fristPassWord)) {
                        ToastUtils.showShortToastSafe(this, "两次密码不一致,请重新输入");
                        mCetSecondPassword.setText("");
                        return;
                    }
                    OkHttpUtils.post().url(UrlUtil.getRegisterUrl()).addParams("memberName", mPhoneNumber).addParams("memberPasswd", fristPassWord)
                            .addParams("checkCode", mAuthCode).build().execute(new MyStringCallBack(this, false) {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            JSONObject parse = (JSONObject) JSON.parse(response);
                            if (parse.getString("error_code").equals(Constant.SUCCESS)) {
                                ToastUtils.showShortToastSafe(RegistActivity.this, parse.getString("msg"));
                                finishThisActivity();
                            } else {
                                String msg = parse.getString("msg");
                                if (msg.contains("忘记密码")) {
                                    ToastUtils.showShortToastSafe(RegistActivity.this, "手机号码:" + mPhoneNumber + "已经注册了");
                                    finishThisActivity();
                                } else {//验证码错误
                                    ToastUtils.showShortToastSafe(RegistActivity.this, msg);
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            mNextClick = false;
                                            mTvActionBarTitle.setText("手机验证");
                                            mBtNext.setText("下一步");
                                            mAllAutoCode.setVisibility(View.VISIBLE);
                                            mAllPassword.setVisibility(View.GONE);
                                            mTvLogin.setVisibility(View.VISIBLE);
                                            mAllWraning.setVisibility(View.INVISIBLE);
                                            mCetAuthcode.setText("");
                                            mAuthCode = "";
                                            mCetFristPassword.setText("");
                                            mCetSecondPassword.setText("");
                                        }
                                    }, 2000);
                                }
                            }
                        }
                    });
                }
                break;
        }
    }

    private void finishThisActivity() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RegistActivity.this.finish();
            }
        }, 2000);
    }

    /*- 倒计时内部类 -*/
    public class MyCounttDownTimer extends CountDownTimer {

        public MyCounttDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mBtGetAuthcode.setText("获取验证码");
            mBtGetAuthcode.setClickable(true);
            mBtGetAuthcode.setSelected(false);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtGetAuthcode.setText((millisUntilFinished / 1000) + " s");
        }
    }
}